package cn.li.test.pattern.observer_java.observer;

import cn.li.test.pattern.observer_java.DisplayElement;
import cn.li.test.pattern.observer_java.subject.WeatherData;

import java.util.Observable;
import java.util.Observer;

public class StatisticsDisplay implements DisplayElement, Observer {

    private float temperature;
    private float humidity;
    private float pressure;
    private Observable subject;

    /**
     * 构造器需要主题用来注册
     * @param subject weatherData
     */
    public StatisticsDisplay(Observable subject){
        this.subject = subject;
        subject.addObserver(this);
    }

    public void unsubscribe(){
        subject.deleteObserver(this);
    }

    @Override
    public void display() {
        System.out.println("Avg Conditions : temperature="+temperature+"° humitidy="+humidity+"% pressure="+pressure+"pa");
    }

    @Override
    public void update(Observable subject,Object arg) {
        WeatherData weatherData = null;
        if(subject instanceof WeatherData) {
            weatherData = (WeatherData) subject;
        }
        this.temperature = weatherData.getTemperature();
        this.humidity = weatherData.getHumidity();
        this.pressure = weatherData.getPressure();
        display();
    }
}
